<!-- 用户终端绑定 -->
<template>
  <div class="view-container">
    <div class="zh-query-box">
      <QueryBox 
      ref="queryBox"
      :content="queryProperty"
      @query="toQuery"
      ></QueryBox>
    </div>
    <div class="zh-table-box">
      <Table 
      :data="tableData" 
      :globalOperate="globalOperate"
      :globalTab="globalTab"
      :columns="tableColumns" 
      :rowOperate="rowOperate"
      :rowOperateProperty="rowOperateProperty"
      :showPrint="showToolbox.showPrint"
      :showImport="showToolbox.showImport"
      :showExport="showToolbox.showExport"
      :showTool="showToolbox.showTool"
      :rowStyle="setRowStyle"
      @pageChange="handlePageChange"
      :page="page"
      ></Table>
    </div>
  </div>
</template>

<script setup lang="tsx">
import Table from "@/components/Table/table.vue"
import QueryBox from "@/components/QueryBox/queryBox.vue";
import user2mid from "./component/user2mid.vue";
import { validatePsidno, validateIP, checkUid, validateUname, checkUname, checkIdpolice, checkPasswd, checkPasswd2 } from "./validate";
import {
  apiListUser,
  apiGetUser,
  apiEditPasswd
} from "@/api/user";

import { useRouter } from "vue-router";

import { ref, watch, onMounted, h, nextTick, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElButton, ElIcon, ElMessage, ElTag } from "element-plus";

defineOptions({
  name: "UserMid",
});

onMounted(async () => {
  initPage()
  initTableProperty()
})

const router = useRouter()

const queryBox = ref()

const initTableProperty = () => {
  initRowOperate()
  tableColumns.value = wholeTableColumns
  globalOperate.value = wholeGlobalOperate
  globalTab.value = wholeGlobalTab
}

const showToolbox = ref({
  showPrint: false,
  showImport: false,
  showExport: false,
  showTool: false
})

const rowOperateProperty = ref({
  width: '180',
  show: true
})

const page = ref({
  page:1,
  pageSize:10,
  total:0
})

const tableData = ref([]);

const tableColumns = ref([])
const wholeTableColumns = [
  {
    align:'left',
    title:'身份证号',
    field: 'uid',
    minWidth: '120px'
  },
  {
    align:'left',
    title:'姓名',
    field:'uname'
  },
  {
    align:'left',
    title:'角色',
    field: 'rid',
    minWidth:'40px',
    render : (dom,props) => {
      return (
        h('div',{class:"operate-box"},
          [h(ElTag, {
            type:props.row.rid === 2 ?'primary':props.row.rid === 3?'success':props.row.rid === 4?'warning':'danger'
          }, ()=>transRole(props.row.rid))]
        )
      )
    }
  },
  {
    align:'left',
    title:'警号',
    field: 'idpolice',
    minWidth:'30px',
    render : (dom,props) => {
      return (
        h('div',{class:"operate-box"},
          [h(ElTag, {
            type: 'primary',
            effect: "plain",
            round:true
          }, ()=>props.row.idpolice)]
        )
      )
    }
  },
  {
    align:'left',
    title:'手机号',
    field:'phone'
  },
  {
    align:'left',
    title:'所属部门',
    field:'org'
  },
  {
    align:'left',
    title:'过期时间',
    field:'expire',
  },
  {
    align:'left',
    title:'创建时间',
    field: 'ct',
    showOverflow:'tooltip'
  },
  {
    align:'left',
    title:'更新时间',
    field: 'ut',
    showOverflow:'tooltip'
  }
]

const transRole = (rid) => {
  let idx = roleList.value.findIndex(item => rid === item.rid)
  return idx !== -1?roleList.value[idx].rname:rid === 1?'超级管理员':'非法角色'
}

const globalTab = ref({})
const wholeGlobalTab = {
}

const necessaryQuery = ref({
  delFlag: 1
})

const getRname = (rid) => {
  if (rid < 1) {
    return '未知角色'
  }
  let idx = roleList.value.findIndex(item => item.rid === rid)
  return idx === -1?'未知角色':roleList.value[idx].rname
}

const globalOperate = ref({})
const wholeGlobalOperate = {
}
const operationList = {
  render : (dom,props) => {
    return (
      h('div',{class:"operate-box"},
        [
        h(ElButton,{
          type: 'success',
          plain: true,
          disabled: props.row.del_flag === 2,
          onClick: ()=>toBindTerm(props.row)
        }, () => "绑定终端")
      ]
      )
    )
  }
}


const rowOperate = ref({})

const initRowOperate = () => {
  rowOperateProperty.value.show = true
  rowOperate.value = operationList
}  

// 分页
const handlePageChange = (val) => {
  page.value = val
  toQuery(queryBox.value.propertyValue)
}

const setRowStyle = ({ rowIndex }) => {
  if (tableData.value.map((item,index) => {
    if (item.del_flag == 2) return index
  }).includes(rowIndex)) {
    return {
      backgroundColor: 'var(--el-disabled-bg-color)',
      color: 'var(--el-disabled-text-color)'
    }
  }
}

const queryProperty = [
  {
    label: '身份证号',
    type: 'input', // 默认有 input,selectbox,date
    labelWidth: 25,
    valueWidth: 75,
    elementName: 'uid',  // 调用方的元素属性名称
    elementValueType: 'string', // 默认 strng,number,array
    elementDefaultValue: '',
    elementWidth: '900',
    elementProperty:{
      placeholder: '请输入用户身份证'
    }
  },
  {
    label: '用户姓名',
    type: 'input', // 默认有 input,selectbox,date
    labelWidth: 25,
    valueWidth: 75,
    elementName: 'name',  // 调用方的元素属性名称
    elementValueType: 'string', // 默认 strng,number,array
    elementDefaultValue: '',
    elementProperty:{
      placeholder: '请输入用户姓名'
    }
  },
  {
    label: '创建时间',
    type: 'date', // 默认有 input,selectbox,date
    labelWidth: 25,
    valueWidth: 75,
    elementName: 'daterange',  // 调用方的元素属性名称
    elementValueType: 'array', // 默认 strng,number,array
    elementDefaultValue: [],
    elementProperty: {
      startPlaceholder:"开始时间",
      endPlaceholder: "结束时间",
      rangeSeparator: "到",
      disabledDate: (time) => {
        return time.getTime() > Date.now(); //禁止选择今天以后的时间
        //return time.getTime() < Date.now() - 8.64e7;//禁止选择今天以前的时间
      },
    }
  },
]

const toQuery = async (data) => {
  var queryParam: Object  = {
    del: necessaryQuery.value.delFlag
  }
  if (data && data.daterange && data.daterange.length){
    queryParam.start_time = formatDate(data.daterange[0])
    queryParam.end_time = formatDate(data.daterange[1])
  }
  if (data.uid.length > 0) queryParam.uid = data.uid
  if (data.name) queryParam.uname = data.name
  if (validateQuery(queryParam))getTableData(queryParam)
}

const validateQuery = (data) => {
  if (data.uid && data.uid.length > 0) {
    if (!validatePsidno(data.uid)) {
      ElMessage({
        type: 'error',
        message: '身份证格式不正确'
      })
      return false
    }
  }
  if (data.uname && data.uname.length > 0) {
    if (!validateUname(data.uname)) {
      ElMessage({
        type: 'error',
        message: '姓名格式不正确'
      })
      return false
    }
  }
  return true
}

function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，需要加1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 查询
const getTableData = async (queryParam) => {
  const table = await apiListUser({
    "userRequest": {
      page_num: page.value.page,
      page_size: page.value.pageSize,
      ...queryParam 
    }
  })
  if (table.code === 200) {
    tableData.value = table.listUserResponse.data;
    page.value =
    {
      total: table.listUserResponse.page.total,
      page: page.value.page,
      pageSize: page.value.pageSize
    }
  }
}

watch(
  () => tableData.value,
  () => {
  }
)

const changeBindRole = async (val) => {
  userList.value = []
  userForm.value.puid = ''
  let rid = 0
  switch (val) {
    case 2:
      return
    case 3:
      rid = 2
      break
    case 4:
      rid = 2
      break
  }
  const res = await apiListUser({ userRequest: { rid: rid } })
  if (res.code === 200) {
    userList.value = res.listUserResponse.data
  }
}


const initPage = async () => {
  getTableData({
    del: necessaryQuery.value.delFlag
  });
}

const roleList = ref([
  {
    rid: 2,
    rname:'实验室审核员'
  },
  {
    rid: 3,
    rname:'实验室研判员'
  },
  {
    rid: 4,
    rname:'普通用户'
  },
])
const userList = ref([])
const userFormRef = ref()

const toBindTerm = async (data?: Object) => {
  router.push({ path: "/usermid2", query: {uid: data.uid}})
}

</script>

<style lang="scss">
.view-container{
  padding: 20px;
  display: flex;
  flex-direction: column;
}
.header-img-box {
  @apply w-52 h-52 border border-solid border-gray-300 rounded-xl flex justify-center items-center cursor-pointer;
}
.query-box{
  width: 100%;
  margin-top: 5px;
}
.zh-query-box {
  @apply p-4 bg-white text-slate-700 dark:text-slate-400 dark:bg-slate-900 rounded my-2;
  border: 1px solid var(--table-border);
}
.zh-table-box {
  @apply p-4 bg-white text-slate-700 dark:text-slate-400 dark:bg-slate-900 rounded my-2;
  border: 1px solid var(--table-border);
  height: 700px;
}
.first{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.dialog-left{
  width: 100%;
}
.dialog-right{
  width: 100%;
  padding-left:10px;
  max-height: 400px;
  overflow: auto;
}
.cube-enter-active,
.cube-leave-active {
	transition: all .7s;
}

.cube-enter-from,
.cube-leave-to {
	transform: translateY(0px) rotateX(40deg);
	opacity: 0;
}

.cube-enter-to,
.cube-leave-from {
	transform: translateY(0) rotateX(0deg);
	opacity: 1;
}
h4{
  text-indent: 1em;
}
.validate-col {
  padding-bottom: 17px;
}
.el-form-item.is-error {
  .ip_input_container{
    box-shadow: 0 0 0 1px var(--el-color-danger) inset;
  }
}
::v-deep(.el-form){
  max-width: 800px !important;
}
.el-form-item--label-top .el-form-item__label{
  margin-bottom: 0px;
}
.el-form-item__label{
  font-size: 14px;
  font-weight: 500;
}
.sub-title{
  border: 1px solid rgb(229,230,235);
  padding: 10px;
  border-radius: 2px;
  transition: box-shadow .2s cubic-bezier(0,0,1,1);
}
.sub-title > .el-form-item__label{
  padding: 0px 0 0 0;
  font-size: 15px;
  font-weight: 600;
  padding-bottom: 10px;
}
</style>
